package com.dsideal.cloud.cas.client.filter;

import com.dsideal.cloud.auth.common.util.jwt.IJWTInfo;
import com.dsideal.cloud.cas.client.properties.RequestProperties;
import com.dsideal.cloud.common.log.DsLogger;
import com.dsideal.cloud.common.util.StringUtils;
import com.dsideal.cloud.cas.client.cache.RedisUserCache;
import com.dsideal.cloud.cas.client.cas.entity.CasUserDetails;
import com.dsideal.cloud.cas.client.utils.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.web.authentication.logout.LogoutFilter;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class CasLogoutFilter extends LogoutFilter {

    private final static DsLogger log = DsLogger.buildLogger(CasLogoutFilter.class);

    @Autowired
    RedisUserCache redisUserCache;
    @Autowired
    JwtTokenUtil jwtTokenUtil;

    @Autowired
    private RequestProperties requestProperties;
    public CasLogoutFilter(LogoutSuccessHandler logoutSuccessHandler, LogoutHandler... handlers) {
        super(logoutSuccessHandler, handlers);
    }

    public CasLogoutFilter(String logoutSuccessUrl, LogoutHandler... handlers) {
        super(logoutSuccessUrl, handlers);
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        super.doFilter(req, res, chain);
        HttpServletRequest request = (HttpServletRequest)req;
        HttpServletResponse response = (HttpServletResponse)res;
        if(super.requiresLogout(request, response)){
            String token = request.getHeader(requestProperties.getTokenHeader());
            // 根据token拿name deleteCache
            if(StringUtils.isNotBlank(token)){
                try {
                    CasUserDetails casUserDetails= getUserFromToken(token);
                    String cacheKey = request.getHeader(requestProperties.getUserAgent())+casUserDetails.getName();
                    redisUserCache.removeTokenFromCache(cacheKey);
                } catch (Exception e) {
                    log.error("CasLogoutFilter error {}", e);
                }
            }

        }

    }

    /**
     * 解析token中的用户信息
     *
     * @param token
     * @return
     */
    private CasUserDetails getUserFromToken(String token) throws Exception {
        IJWTInfo jwtInfo = jwtTokenUtil.getInfoFromToken(token);
        return CasUserDetails.fromJWTInfo(jwtInfo);
    }
}
